package com.cyh.ebptasywar.common;

import com.cyh.ebptasywar.common.config.JobDetailConfig;
import com.cyh.ebptasywar.job.PromptWorkJob;
import com.cyh.ebptasywar.trigger.PromtWorkTrigger;
import com.cyh.ebptpubjar.ebptlogger.EbptLogger;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * 调度器工厂根据配置创建实例并且配置job和trigger
 */
@Configuration
public class SchedulerFactory {

    /**
     * 配置线程数量
     */
    private String threadPoolClass;

    /**
     * Trigger类
     */
    @Autowired
    private PromtWorkTrigger promtWorkTrigger;
    /**
     * job类
     */
    @Autowired
    private PromptWorkJob promptWorkJob;

    @Autowired
    private JobDetailConfig jobDetailConfig;

    /**
     * 根据配置来创建PromptWorkSchedulerFactory
     * @return
     * @throws SchedulerException
     */
    @Bean("PromptWorkSchedulerFactory")
    public List<Scheduler> createPromptWorkSchedulerFactory() throws SchedulerException {
        EbptLogger.info(getClass(),"初始化schedulerFactory");
        List<Scheduler> schedulerList = new ArrayList<>();
        StdSchedulerFactory schedulerFactory = new StdSchedulerFactory();
        Properties props = new Properties();
        props.put(StdSchedulerFactory.PROP_THREAD_POOL_CLASS, "org.quartz.simpl.SimpleThreadPool");
        // TODO 暂时配置成3
        props.put("org.quartz.threadPool.threadCount", "3");
        // TODO 暂时生成3个
        for(int i = 0;i< 3;i++){
            // 配置instancName
            props.put("org.quartz.scheduler.instanceName", "PromptWorkScheduler-"+i);
            schedulerFactory.initialize(props);
            Scheduler scheduler = schedulerFactory.getScheduler();
            EbptLogger.info(getClass(),"初始化scheduler:[{}]",scheduler);
            scheduler.scheduleJob(jobDetailConfig.promptWorkJobDetail(),promtWorkTrigger.CronTrigger());
            scheduler.start();
            schedulerList.add(scheduler);
        }
        EbptLogger.info(getClass(),"初始化schedulerFactory-完成");
        return schedulerList;
    }

}
